package cq.zhcqk.util.update;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;

import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by zhangle on 2017/5/25.
 */
public class UpdateXmlUtil {
    private String TAG = "版本更新：";
    String httpUrl = ApiAdressHelper.UPDATE_URL;


    private Context context;
    private UpdataInfo info = null;

    //进度条
    private BuildBean buildBean;

    public UpdateXmlUtil(Context context) {
        this.context = context;
        //加载动画
        buildBean = DialogUIUtils.showLoading(context, "正在检查", false, true, false, false);
    }

    public void Update(){
//        buildBean.show();

        new Thread(){
            @Override
            public void run(){
                //需要在线程执行的方法
                try {
                    InputStream is = getXml();   //获取xml内容
                    info = getUpdataInfo(is);  //调用解析方法
                    Log.i(TAG, "check--infoVersion="+info.getServerVersion()+"，infoURL="+info.getUrl()
                            +"，infoAbout="+info.getUpdateDescription()+"，url="+info.getUrl());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //给handler发送一个消息
                mHandler.sendEmptyMessage(new Message().what=1);
            }
        }.start();
    }
    //Handler消息接收机制
    private Handler mHandler =new Handler(){
        //Handler接收到相应消息进行刷新ui等操作
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            if(msg.what == 1){
                //收到消息，在此进行ui相关操作，如将解析的内容显示出来。
                initUpdate();
//                DialogUIUtils.dismiss(buildBean);
            }
        }

    };

    /**
     * 启动更新
     */
    private void initUpdate(){
        if(info != null){
            UpdateManager mUpdateManager = new UpdateManager(context,info.getServerVersion(),getLocal(),info.getUpdateDescription(),info.isForceUpdate(),info.getUrl());
            mUpdateManager.showNoticeDialog();
        }
    }

    /**
     * 解析XML
     * @param is
     * @return
     * @throws Exception
     */
    public UpdataInfo getUpdataInfo(InputStream is) throws Exception{
        UpdataInfo info = null;
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "UTF-8");//设置解析的数据源，编码格式
        int event = parser.getEventType();
        while(event != XmlPullParser.END_DOCUMENT ){
            switch (event) {
                case XmlPullParser.START_DOCUMENT: //开始解析
                    //可在此做初始化相关工作
                    info = new UpdataInfo();
                    Log.i("UpdatePullParser", "--START_DOCUMENT--");
                    break;
                case XmlPullParser.START_TAG:
                    Log.i("UpdatePullParser", "--START_TAG--");
                    String tag = parser.getName();
                    if("serverVersion".equals(tag)){
                        info.setServerVersion(new Integer(parser.nextText())); //获取版本号
                    }else if ("updateDescription".equals(tag)){
                        info.setUpdateDescription(parser.nextText()); //获取url地址
                    }else if ("forceUpdate".equals(tag)){
                        info.setForceUpdate(new Boolean(parser.nextText())); //获取相关信息
                    }else if ("url".equals(tag)){
                        info.setUrl(parser.nextText()); //获取相关信息
                    }
                    break;
                case XmlPullParser.END_TAG://读完一个元素，如有多个元素，存入容器中
                    break;
                default:
                    break;
            }
            event = parser.next();
        }
        return info;   //返回一个UpdataInfo实体
    }

    /**
     * 获取XML
     * @return
     * @throws Exception
     */
    public InputStream getXml() throws Exception {
        String TAG="URLConnect";

        HttpURLConnection conn = (HttpURLConnection)new URL(httpUrl).openConnection();
        conn.setReadTimeout(5*1000);  //设置连接超时的时间
//    conn.setRequestMethod("GET");
        conn.connect(); //开始连接
        if(conn.getResponseCode() == 200){
            InputStream is = conn.getInputStream();
            return is;   //返回InputStream
        } else {
            Log.e(TAG, "---连接失败---");
        }
        conn.disconnect(); //断开连接
        return null;
    }

    /**
     * 获取本地版本号
     * @return
     */
    private int getLocal() {
        int mLocalVersion = 0;
        PackageInfo packageInfo;
        try {
            packageInfo = context.getApplicationContext()
                    .getPackageManager().getPackageInfo(context.getPackageName(), 0);
            mLocalVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return mLocalVersion;
    }
    }
